package com.gxa.shop.servlet.address;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxa.shop.commons.r.R;
import com.gxa.shop.service.address.AddressService;
import com.gxa.shop.service.address.impl.AddressServiceImpl;
import com.gxa.shop.util.MyFormatUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;

@WebServlet(name = "DeleteAddressServlet",value = "/address/delete")
public class DeleteAddressServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 通过bufferReader
//        BufferedReader reader=req.getReader();
//        // 使用BufferedReader的lines()方法获取流，然后使用Collectors.joining()将所有行连接成一个单一的字符串。
//        String data=reader.lines().collect(Collectors.joining());
//        //  使用JSON.parseObject(data)将字符串data解析为JSONObject对象。
//        JSONObject jsonObject= JSON.parseObject(data);
//        Integer id= jsonObject.getInteger("addressId");
        Integer id= MyFormatUtils.toInteger(req.getParameter("addressId"));
        AddressService addressService=new AddressServiceImpl();

        int row=addressService.deleteAddress(id);
        R r;
        if (row>0){
            r=R.ok("删除成功");
        }else {
            r=R.error("删除失败");
        }
        String jsonResult=JSON.toJSONString(r);
        // 变成流，响应给前端
        PrintWriter writer=resp.getWriter();
        writer.write(jsonResult);
        writer.flush();
        writer.close();

    }
}
